from zope.app.pagetemplate import ViewPageTemplateFile

from zope.formlib import form

from dbformlib.browser import DBFormlibEditForm
from dbformlib.browser import DBFormlibAddForm
from dbformlib.browser import DBFormlibDeleteForm
from dbformlib.browser import DBFormlibViewForm
from dbformlib.browser import DBFormlibForm

from interfaces import IDBTestContent


class DBTestEditForm(DBFormlibEditForm):

    def define_fields(self):
        self.form_fields = form.Fields(IDBTestContent)
        self.form_fields['name'].for_display = True


class DBTestAddForm(DBFormlibAddForm):

    def define_fields(self):
        self.form_fields = form.Fields(IDBTestContent)
        self.form_fields = self.form_fields.omit('row_id', 'group_id')
        
    def nextURL(self, result):
        # after adding new row we may redirect to it's edit form
        return '@@edit.html?in.row_id=%s' % (result)

class DBTestDeleteForm(DBFormlibDeleteForm):

    def define_fields(self):
        self.form_fields = \
                 form.Fields(IDBTestContent).select('name',
                                                    'row_id',
                                                    'group_id')        


class DBTestViewForm(DBFormlibViewForm):

    def define_fields(self):
        self.form_fields = \
                 form.Fields(IDBTestContent)        

class DBTestCustomForm(DBFormlibForm):
    template = ViewPageTemplateFile('custom.pt')

    def define_fields(self):
        self.form_fields = \
                 form.Fields(IDBTestContent)
                 
    @form.action('Change')
    def handle_change_action(self, action, data):
        da = self.get_data_obj()
        changed = False
        changed, result, errors = da.apply_data(self.form_fields, data)
        if errors:
            self.errors = errors
            self.status = u'There were errors'
        elif changed:
            self.status = u'OK!'
        else:
            self.status = u'No changes'
            
    @form.action('Cancel', validator=lambda *a: ())  # hack to omit validation
    def handle_choicer_action(self, action, data):
        self.request.response.redirect('http://localhost:8080')